无法在.then回调函数中执行代码?

时间:2019-02-21 15:39:50

标签: javascript promise callback axios

如何在以下代码的最后一个注释处执行代码?由于某些原因,我不允许这样做。我的评论不在回调函数中吗?

代码是Stackoverflow上几个答案的结果,我不太了解发生了什么。

browser.browserAction.onClicked.addListener(async tab => {

    const contentScriptReady = Promise.all([
        browser.tabs.executeScript(tab.id, {file: "axios.min.js"}),
        browser.tabs.executeScript(tab.id, {file: "content.js"}),
        browser.tabs.executeScript(tab.id, { file: "sweetalert2.all.min.js" }),
        browser.tabs.insertCSS(tab.id, { file: "styles.css" })
    ]);

    const connectionStatus = {};

    async function getConnectionStatusData(logicalAddress) {

        let cooperations = await axios.get('http://api.ntjp.se/coop/api/v1/cooperations.json', {
        params: {
          connectionPointId: connectionPointId,
          logicalAddressId: logicalAddressId,
          serviceDomainId: serviceDomainId,
          serviceConsumerId: serviceConsumerId,
          include: "serviceContract"
         }
        });

        /* some more let x = await axios.get... */

        connectionStatus.supportedServiceContracts = await Promise.all( cooperations.data.map(cooperation => axios.get('http://api.ntjp.se/coop/api/v1/serviceProducers.json', {
          params: {
            connectionPointId,
            logicalAddressId,
            serviceDomainId,
            serviceConsumerId,
            serviceContractId: cooperation.serviceContract.id,
          },
           }).then(response => ({ // I want to process the response but I can't put executable code here
            serviceContract: cooperation.serviceContract.namespace,
            serviceProducerDescription: response.data[0].description,
            serviceProducerHSAId: response.data[0].hsaId,
            }))
          )
        );

        await contentScriptReady;
        browser.tabs.sendMessage(tab.id, connectionStatus);

    }

});

1 个答案:

答案 0 :(得分:1)

这是object literal returned from an arrow function。您不能在其中发表声明。您将需要将其重写为

….then(response => {
    console.log("example");  // executable code here
    return {
        serviceContract: cooperation.serviceContract.namespace,
        serviceProducerDescription: response.data[0].description,
        serviceProducerHSAId: response.data[0].hsaId,
    };
})