在map函数中,如果名称为“ Startpoint”,则想调用一个异步函数,如果名称为“ Question”,则要调用相同的函数。这些函数调用API(来自dialogflow)。我有一个问题,第二个函数调用会取代第一个函数。
我如何确定它首先以“起点”函数调用开始,并等待直到解决该问题以启动下一个函数?
代码如下:
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);
这是功能saveNodeasIntentinDialogflow(简体):
const saveNodeAsIntentinDialogflow = async (someParameter) => {
try {
const res = await axios.post(
`https://dialogflow.googleapis.com/v2/projects/agent/intents:batchUpdate`)}
一种可行的解决方案是将它们分成两个不同的地图
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));
为什么必须在map函数中?只需迭代数组并等待。
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`);
}