[英]How can I be sure that it first starts with the “Startpoint” function call and waits until this one is resolved to start the next function call?
Within a map function, I want to call an asynchronous function if the name is "Startpoint" and the same function if the name is "Question". Within a map function, I want to call an asynchronous function if the name is "Startpoint" and the same function if the name is "Question". These functions call an API (from dialogflow).
这些函数调用 API(来自 dialogflow)。 I have the problem that the second function call overtakes the first one.
我有第二个 function 调用超过第一个的问题。
How can I be sure that it first starts with the "Startpoint" function call and waits until this one is resolved to start the next function?我如何确定它首先从“起点”function 调用开始,然后等到该调用解决后开始下一个 function?
Here is the code:这是代码:
const editorJSON = {1: "Startpoint", 2: "Answer", 3: "Question"};
Object.keys(editorJSON).map((key, index) => {
if (editorJSON[key].name === "Startpoint") {
saveNodeasIntentinDialogflow(someArgument);
if (editorJSON[key].name === "Question") {
saveNodeasIntentinDialogflow(someArgument);
And here is the function saveNodeasIntentinDialogflow (simplified):这是 function saveNodeasIntentinDialogflow(简化):
const saveNodeAsIntentinDialogflow = async (someParameter) => {
try {
const res = await axios.post(
`https://dialogflow.googleapis.com/v2/projects/agent/intents:batchUpdate`)}
One working solution is to split them up into two different maps一种可行的解决方案是将它们分成两个不同的地图
const editorJSON = { 1: "Startpoint", 2: "Answer", 3: "Question" }; //console logged at end to show output order const order = []; //longer async async function mockLonger(param) { return await new Promise(function(resolve, reject) { setTimeout(() => resolve(order.push(param)), 2000); }) } //shorter async async function mockShorter(param) { return await new Promise(function(resolve, reject) { setTimeout(() => resolve(order.push(param)), 1000); }) } //async map async function mapArray(array) { console.log("processing..."); const resultsA = array.map(async(key, index) => { if (editorJSON[key] === "Startpoint") await mockLonger("longer"); }) //process longer call first await Promise.all(resultsA) const resultsB = array.map(async(key, index) => { if (editorJSON[key] === "Question") await mockShorter("shorter"); }) //then shorter call await Promise.all(resultsB) console.log("Output Order:", order) } mapArray(Object.keys(editorJSON));
Why does it have to be within a map function?为什么它必须在 map function 内? Just iterate the array and await.
只需迭代数组并等待。
const editorJSON = {1: "Startpoint", 2: "Answer", 3: "Question"}; (async () => { for (const value of Object.values(editorJSON)) { await saveNodeasIntentinDialogflow(value); } })(); async function saveNodeasIntentinDialogflow(name) { await new Promise(r => setTimeout(r, 3000 * Math.random())); console.log(`${name} is done`); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.