使用async / await进行并行调用的正确方法
我正在努力如何在nodejs中正确地做到这一点。这试图并行做两件事:
- 使用axios下载网页
- 创建一个目录
完成后:
- 将结果异步保存到de created目录中的文件
然后等到完成
const uuidv1 = require('uuid/v1')
const fs = require('fs')
const util = require('util')
const axios = require('axios')
const path = require('path')
const mkdir = util.promisify(fs.mkdir)
const writeFile = util.promisify(fs.writeFile)
const downloadPage = async (url='') => {
console.log('downloading ', url)
const fetchPage = async function() {
const folderName = uuidv1()
return axios
.all([
mkdir(folderName),
axios.get(url)
])
.then(axios.spread(function (f, r) {
writeFile(path.join(__dirname, folderName, 'file.html'), r.data);
}));
}
await fetchPage()
}
downloadPage(process.argv[2])
回答如下:
你的问题和样本看起来很矛盾。问题是,您需要使用async和await来进行并行调用,但是示例代码显示您需要顺序调用而不是并行调用。
最好使用Async / Awaits进行顺序调用。
async函数是'Promise'的一种简写函数,事情是隐式完成的,就像返回一样会被视为'resolve'。
await应始终在异步函数内,在继续进行之前添加等待您需要等待的函数。
await函数中的语法更改是,而不是
somePromiseFunctionCall().then( (someVarible) => {...}).catch(e => {})
你需要使用
const asyncFunction = async (parameters) => {
try {
// First Function call that returns Promise / async
someVariable = await somePromiseFunctionCall();
// Second (sequential) call that returns Promise / async
someNewVariable = await someotherPromiseFunctionCall();
} catch(e) {
throw new Error(e);
}
}
现在,在您的示例中,如果您的要求是等待axios返回然后创建文件夹然后将结果写入文件,则可以使用async和await来完成。
使用async / await进行并行调用的正确方法
我正在努力如何在nodejs中正确地做到这一点。这试图并行做两件事:
- 使用axios下载网页
- 创建一个目录
完成后:
- 将结果异步保存到de created目录中的文件
然后等到完成
const uuidv1 = require('uuid/v1')
const fs = require('fs')
const util = require('util')
const axios = require('axios')
const path = require('path')
const mkdir = util.promisify(fs.mkdir)
const writeFile = util.promisify(fs.writeFile)
const downloadPage = async (url='') => {
console.log('downloading ', url)
const fetchPage = async function() {
const folderName = uuidv1()
return axios
.all([
mkdir(folderName),
axios.get(url)
])
.then(axios.spread(function (f, r) {
writeFile(path.join(__dirname, folderName, 'file.html'), r.data);
}));
}
await fetchPage()
}
downloadPage(process.argv[2])
回答如下:
你的问题和样本看起来很矛盾。问题是,您需要使用async和await来进行并行调用,但是示例代码显示您需要顺序调用而不是并行调用。
最好使用Async / Awaits进行顺序调用。
async函数是'Promise'的一种简写函数,事情是隐式完成的,就像返回一样会被视为'resolve'。
await应始终在异步函数内,在继续进行之前添加等待您需要等待的函数。
await函数中的语法更改是,而不是
somePromiseFunctionCall().then( (someVarible) => {...}).catch(e => {})
你需要使用
const asyncFunction = async (parameters) => {
try {
// First Function call that returns Promise / async
someVariable = await somePromiseFunctionCall();
// Second (sequential) call that returns Promise / async
someNewVariable = await someotherPromiseFunctionCall();
} catch(e) {
throw new Error(e);
}
}
现在,在您的示例中,如果您的要求是等待axios返回然后创建文件夹然后将结果写入文件,则可以使用async和await来完成。
与本文相关的文章
评论列表 (0)
- 暂无评论