use*_*553 14 javascript node.js async-await
试图在Javascript中学习异步模式,但它似乎没有等待以下行.在以下示例中,集合是请求对象,而不是实际解析的正文.是不是await应该等待请求完成?
async function importUsers(endpoint) {
const options = {
data: search,
uri: endpointCollection,
headers,
}
try {
const collection = await browser.post(options, (err, res, body) => JSON.parse(body))
// collection is the request object instead of the result of the request
const users = await collection.data.forEach(item => parseUserProfile(item));
await users.forEach(user => saveUserInfo(user))
} catch(err) {
handleError(err)
}
}
async function parseUserProfile({ username, userid }) {
const url = userProfileString(username)
try {
const profile = await browser.get(url, headers, (err, res, body) => {
return { ... } // data from the body
})
} catch(err) {
handleError(err)
}
}
Run Code Online (Sandbox Code Playgroud)
Get*_*awn 10
Async/Await仅适用于返回(并解析)promise的函数.
以下示例将在3秒后写入控制台,然后继续.
// Tell the browser that this function is asynchronous
async function myFunc() {
// Await for the promise to resolve
await new Promise((resolve) => {
setTimeout(() => {
// Resolve the promise
resolve(console.log('hello'));
}, 3000);
});
// Once the promise gets resolved continue on
console.log('hi');
}
// Call the function
myFunc();Run Code Online (Sandbox Code Playgroud)
没有async/await,输出如下:
hi
hello
Run Code Online (Sandbox Code Playgroud)
这将是因为hi输出将运行,然后在3秒后超时将运行.
但是使用async/await,输出如下所示:
// Tell the browser that this function is asynchronous
async function myFunc() {
// Skip await
new Promise((resolve) => {
setTimeout(() => {
// Resolve the promise
resolve(console.log('hello'));
}, 3000);
});
// Since await was not used, this will print first
console.log('hi');
}
// Call the function
myFunc();Run Code Online (Sandbox Code Playgroud)
这是因为我们等待超时然后我们运行hi输出.
await 应该期待一个承诺,对于回调样式的异步函数,您可以将其转换为:
new Promise((resolve, reject) => browser.post(options, (err, res, body) => resolve(JSON.parse(body))))
Run Code Online (Sandbox Code Playgroud)
对于一个数组,你需要将它映射到一个promise数组,然后使用Promise.all将它变成一个'promise of array',例如:
Promise.all(collection.data.map(item => parseUserProfile(item)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19425 次 |
| 最近记录: |