为什么这个呼叫在继续之前没有等待响应

Why does this call not wait for the response before continuing?

本文关键字:等待 响应 继续 呼叫 为什么      更新时间:2023-09-26

当我运行此代码时,这是Chrome调试工具中的结果:

需要加载元数据Init之后成品z

我原以为"after-init"只会在"finished z"代码启动后出现,但它似乎在之前返回。为什么会这样?(我是JS中promise和异步编程的新手)

Class1.js:

 function activate()
    {
        dataServiceHelper.initBreezeMetaData().then(console.log('after Init'));
    }

dataServiceHelper.js:

function initBreezeMetaData()
{
    if (manager.metadataStore.isEmpty())
    {
        console.log('need to load metadata');
        return manager.fetchMetadata().then(function ()
        {
            console.log('loaded metadata for ' + config.serviceUrl);
        }).fin(function ()
        {
            console.log('finished z');
        });
    } else
    {
        return true;
    }
}
.then(console.log('after Init'));

在这里,调用console.log并将结果(undefined)传递给then。您需要传递一个回调函数,就像在initBreezeMetaData:中所做的那样

dataServiceHelper.initBreezeMetaData().then(function() {
    console.log('after Init');
});

return true;

如果initBreezeMetaData函数返回promise,则它应该始终返回promise。当调用者想要对结果调用.then方法时,返回布尔值会导致异常…