Gus*_*Gus 7 javascript google-translate promise
我有这个 JS 对象:
let setOfWords = {
"nouns": [
"work",
"construction",
"industry"
],
"verbs": [
"work"
],
}
Run Code Online (Sandbox Code Playgroud)
我正在使用调用 REST 资源的 google translate API,所以我需要等待每个翻译的响应,然后解析相同的对象结构,但使用翻译的单词。
function translateByCategory(){
let translatedObj = {};
return new Promise(function(resolve, reject){
Object.keys(obj).forEach(function(category){
if (translatedObj[category] == undefined) {
translatedObj[category] = [];
}
setOfWords.forEach(function(word){
google.translate(word, 'es', 'en').then(function(translation){
translatedObj[category].push(translation.translatedText);
});
});
// return the translatedObj until all of the categories are translated
resolve(translatedObj);
});
});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Promise.all()等待所有承诺履行(或第一次拒绝)
var translateRequests = [];
Object.keys(setOfWords).forEach(function(category){
setOfWords[category].forEach(function(word){
translateRequests.push(google.translate(word, 'es', 'en'));
});
});
});
Promise.all(translateRequests).then(function(translateResults){
//do something with all the results
});
Run Code Online (Sandbox Code Playgroud)
请参阅此处的文档:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all