我正在测试 node-fetch,当我使用 async/await 时,出现了一个问题:如果我在其中使用 await,我必须使我的函数异步但由于我的函数是异步的,我需要等待它并使父函数异步。等等......上下文:
async functionA()
{
var result = await functionB();
}
async functionB()
{
//do things
var result = await functionC();
//do things
var blob;
//do things
return blop;
}
async functionC()
{
//here is the real async call
var result = await fetch(....);
var json = await result.json();
return json;
}
}
我怎样才能让这个异步/等待链接停止?我的程序中有一种使用 fetch 的方法,它将使我将所有其他方法转换为异步方法。这真的是所有其他用 fetch 开发的程序的样子吗?可能是我对 async/await 的理解不够。
感谢您的时间:)
答案 0 :(得分:2)
在脚本的开头调用异步函数一次。在它的响应返回后,使用结果同步调用脚本的其余部分。类似的东西:
async function functionC() {
//here is the real async call
const response = await fetch(....);
const result = await result.json();
return result;
}
functionC()
.then((results) => {
// do stuff with results
functionA(results);
functionB(results); // if needed
// etc
})
.catch(handleErrors); // don't forget this part
这样,脚本中只有一部分——靠近入口点——需要处理异步逻辑。实现这一点可能需要进行一些重构,但与使所有内容异步的替代方案相比,这是值得的。
(另请注意,.json
解析为普通对象或数组,可能 - 它不会解析为 JSON 格式的字符串,它解析响应流就好像它是JSON 并解析为结果,该结果不再是 JSON 格式的字符串,而是一个普通值,通常是一个对象或数组)
答案 1 :(得分:1)
从非异步方法调用异步方法。
简答:
int GetData(DateTime x)
{
Task<int> taskGetData = Task.Run( () => GetDataAsync(x));
taskGetData.Wait();
return taskGetData.Result;
}
async Task<int> TaskGetDataAsync(DateTime x)
{
...
}
更长的答案:每当 GetDataAsync 正在等待时(例如,等到数据写入文件或从数据库中提取),您的过程就可以自由地做其他事情。
int GetData(DateTime x)
{
Task<int> taskGetData = Task.Run( () => GetDataAsync(x));
DoSomethingElse();
taskGetData.Wait();
int taskResult = taskGetData.Result;
return taskResult;
}