简体   繁体   English

在带有回调的外部库中获取异步 function 以同步工作

[英]Getting asynchronous function in external library with callback to work synchronously

I am using a library call to connect to my vendor.我正在使用库调用来连接到我的供应商。 The libary call requires a callback in the call.库调用需要在调用中进行回调。 Without a callback in the function, I can easily make this synchronous.在 function 中没有回调,我可以轻松地使其同步。 With the Callback, everything I do is stuck in the callback and never bubbles it way out.使用回调,我所做的一切都停留在回调中,永远不会冒泡。

I have literally tried 100 different ways to get this to work.我确实尝试了 100 种不同的方法来让它发挥作用。

function removeFromDNC(emailAddress, accessToken_in) 
{
    return new Promise( function(resolve, reject) 
    {
        try{
            const options = 
            {   
                auth: {
                accessToken: accessToken_in
                }
                , soapEndpoint: 'https://webservice.XXX.exacttarget.com/Service.asmx' 
            };

            var co = {
                "CustomerKey": "DNC",
                "Keys":[
                    {"Key":{"Name":"Email Address","Value": emailAddress}}]
            };

            var uo = {
                SaveOptions: [{"SaveOption":{PropertyName:"DataExtensionObject",SaveAction:"Delete"}}]
              };


            const soapClient = new FuelSoap(options); 
           //again, I don't control the structure of the next call.          
            let res = soapClient.delete('DataExtensionObject', co, uo, async function( err, response ) {
                if ( err ) {
                    // I can get here, but my reject, or if I use return, does nothing
                    
                     reject();
                }else{
                    // I can get here, but my reject, or if I use return, does nothing
                    resolve();
                }
            });
            console.log("res value " + res);  // undefined - of course
            
        }catch(err){
            console.log("ALERT:  Bad response back for removeFromDNC for email: " + emailAddress + " error: " + err);
            console.log("removeFromDNC promise fulfilled in catch");
            reject();  
        }
    });   
}

Both methods resolve and reject expect parameters, which are res and err in your case.两种方法都resolvereject期望参数,在您的情况下是reserr
As far as removeFromDNC returns a Promise instance, you should call it using either async/await syntax:至于removeFromDNC返回一个Promise实例,您应该使用 async/await 语法调用它:

const res = await removeFromDNC(...);

or chaining then/catch calls:或链接 then/catch 调用:

removeFromDNC(...)
  .then((res) => { ... })    // resolve
  .catch((err) => { ... })   // reject

EDIT:编辑:
If you want to avoid usage of callbacks inside removeFromDNC , consider promisifying of soapClient.delete call.如果您想避免在removeFromDNC中使用回调,请考虑soapClient.delete调用 Refer to util.promisify() if you working in Node.js or use own implementation.如果您在 Node.js 中工作或使用自己的实现,请参阅util.promisify()

Here is the example for demonstration:这是演示的示例:

 const promisify = (fun) => (...args) => { return new Promise((resolve, reject) => { fun(...args, (err, result) => { if(err) reject(err); else resolve(result); }) }) } const soapClient = { delete: (value, cb) => { setTimeout(() => cb(null, value), 10); } }; async function removeFromDNC(emailAddress, accessToken_in) { const soapDelete = promisify(soapClient.delete.bind(soapClient)); const res = await soapDelete('Soap Responce'); //You can use res here return res; } removeFromDNC().then(res => console.log(res))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM