我知道这里不是第一个问题,但是我尝试与其他answers一起使用,但是我的代码无法正常工作。我有一个 Promise.all ,在那里我可以多次提取。提取的结果我变成一个json,然后再开始。完成所有操作后,它应该打印“ done”,当然还会显示更多代码。但是,发生的情况是立即打印出“完成”,然后将提取结果一一打印出来。
这是我的代码:
Promise.all(selectedTypes.map((type) => {
let body = {
selectedScreenshot: type,
dataUrl: dataUrl
};
fetch(URL, {
method: 'POST',
body: JSON.stringify(body),
credentials: 'same-origin',
})
.then(resp => {
console.log(resp.json()); // this is done one by one as the results come in
console.log('next');
})
}
)).then(text => {
console.log('done'); // this should be printed last, is printed first
})
我在做什么错?
答案 0 :(得分:1)
您需要返回fetch
并在fetch().then()
中返回一些结果,这是Promise.all的一些有用信息和示例
selectedTypes = ["https://jsonplaceholder.typicode.com/todos/1", "https://jsonplaceholder.typicode.com/todos/2"]; // My example
Promise.all(selectedTypes.map((type) => {
let body = {
//selectedScreenshot: type,
//dataUrl: dataUrl
};
var URL = type;
//You need to return the fetch
return fetch(URL, {
// method: 'POST',
// body: JSON.stringify(body),
}).then((resp) => resp.json()) // Transform the data into json
.then(function (data) {
console.log(data); // this is done one by one as the results come in
console.log('next');
// you need to return the data
return data;
});
}
)).then(text => {
text.forEach(function (item) {
console.log('FROM PROMISE ALL');
console.log(item);
});
console.log('done'); // this should be printed last, is printed first
});
我仅添加了一些json链接,并评论了您的问题中未声明的所有内容