Javascript 为什么异步等待返回承诺对象而不是我自己的值?
我在select上有一个事件,在这个select中我需要得到一个名为Javascript 为什么异步等待返回承诺对象而不是我自己的值?,javascript,jquery,json,Javascript,Jquery,Json,我在select上有一个事件,在这个select中我需要得到一个名为init()的函数 init()函数调用另一个函数,getManifestJsonFilePath() 在getManifestJsonFilePath()中,我需要检查它在json文件中是否具有已声明并返回相同值的相同对象 在init()中,我还需要将getManifestJsonFilePath()的返回值声明给变量。但不幸的是,getManifestJsonFilePath()函数返回以下内容: 承诺{:未定义} $(“#
init()的函数代码>
init()
函数调用另一个函数,getManifestJsonFilePath()
在getManifestJsonFilePath()
中,我需要检查它在json文件中是否具有已声明并返回相同值的相同对象
在init()
中,我还需要将getManifestJsonFilePath()
的返回值声明给变量。但不幸的是,getManifestJsonFilePath()
函数返回以下内容:
承诺{:未定义}
$(“#城市”).更改(功能(e){
e、 预防默认值();
$(“#bookingSearchBtn”).removeAttr('disabled');
manifestJsonFile=“/json/r”+city.val()+”-c1.json”;
//log(getManifestJsonFilePath(manifestJsonFile));
init();
});
异步函数getManifestJsonFilePath(文件名,路径='build'){
wait manifestFile;//需要上传的json文件
manifestFileResponse=manifestFile.responseJSON;
$.each(manifestFileResponse,函数(i,项){
如果(i==文件名){
退货项目;
}
});
}
让我们来获取JSON;
异步函数init(){
等待getManifestJsonFilePath(manifestJsonFile);
urlJson=getManifestJsonFilePath(manifestJsonFile);
等待你的到来;
log(urlJson);
}
在这里,我已经解决了第一个getManifestJsonFilePath()函数可能不是异步的问题,因为它在页面重新加载时上载了select manifestFile之后工作。下面是代码:
city.change(function(e){
e.preventDefault();
$('#bookingSearchBtn').removeAttr('disabled');
manifestJsonFile = "/json/r" + city.val() + "-c1.json";
// console.log(getManifestJsonFilePath(manifestJsonFile));
init();
});
async function init(){
await getManifestJsonFilePath(manifestJsonFile);
urlJson = getManifestJsonFilePath(manifestJsonFile);
console.log(urlJson);
}
问题在于,每个I只在每个函数中返回值,每个函数都给出值
我已经决定用一种简单的方法来解决这个问题
function getManifestJsonFilePath(filename, path = 'build')
{
manifestFileResponse = manifestFile.responseJSON;
let fileName;
$.each(manifestFileResponse, function(i, item){
if (i === filename){
fileName = item
return false;
}
else{
fileName = "false message"
}
});
return fileName
}
正如你所看到的,我正在使用aync,请不要承诺,请帮助我。我无法理解为什么它返回promiseTry,将您的init函数调用更改为async function init(){let urlJson=await getManifestJsonFilePath(manifestJsonFile);console.log(urlJson);}
async/await将只返回promise对象,您必须处理它。当您进行ajax调用时——承诺确保调用已完成并且状态为成功或失败,这样您就可以处理下一个函数了!