从Promise返回。all不从包装函数返回

时间:2018-08-29 09:50:52

标签: javascript node.js promise

如果 public ActionResult ShopifyAddProduct(string str) { string Productadd = ""; str = ""; var variant = new Variant { option1 = "First", sku = "123", price = "10.00" }; List<Variant> list = new List<Variant>(); list.Add(variant); var obj = new Product { title = "Burton Custom Freestlye 151", product_type = "Snowboard", body_html = "<strong>Good snowboard!</strong>", vendor = "Burton", variants = list }; var product = new RootObject { product = obj }; string json = new JavaScriptSerializer().Serialize(product); ShopifyAuthorizationState hell = new ShopifyAuthorizationState(); ShopifyAPIClient ShopifyProduct = new ShopifyAPIClient(hell); try { var AccessToken = _IntegrationServices.GetAccessToken(User.CompanyId, "2");//2 for Shopify, will create enum later. String username = "apikey"; String password = "apipass"; String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(AccessToken)); hell.AccessToken = encoded;//ShopifyToken.ConfigValue1; hell.ShopName = ShopifyToken.ApplicationName; // string str = SetShopifyStoreProduct(Request); System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var ShopProductResp = ShopifyProduct.Call(ShopifyAPIClient.HttpMethods.POST,"/admin/products.json", json); 解析后满足某些条件,我想从函数返回。但是return语句似乎无效,函数继续执行。

这是我的代码:

Promise.all

2 个答案:

答案 0 :(得分:2)

如果您希望返回Promise链中的某项,则必须返回Promise.all

function somefunc() {

    return Promise.all([match2, match3, match4, match5]).then(results => {
        console.log(results);
        if(results.indexOf(false) > -1) {
            return; // has an effect. somefunc() will return. 
        }
        else {
            // ............
        };

    }).catch(err => {
      console.log(err);
    });

    // this will not get executed after the return staement
}

答案 1 :(得分:1)

Promise.all([是异步解析的,因此// this continues to get executed even after the return staement将始终在then中的代码运行之前执行。

您必须使用await / async

async function somefunc() {
  try {
    var results = await Promise.all([match2, match3, match4, match5]);

    if (results.indexOf(false) > -1) {
      return;
    } else {
      // ............
    };
  } catch (err) {
    console.log(err);
  }

  // code that is executed if return is not done
}

或者您需要在那时内移动// this continues to get executed even after the return staement的代码,并且应该从函数中return来实现Promise链,这样,如果有人调用somefunc可以等待完成功能:

function somefunc() {

  return Promise.all([match2, match3, match4, match5]).then(results => {
    console.log(results);
    if (results.indexOf(false) > -1) {
      return; // has no effect. somefunc() does NOT return. 
    } else {
      // ............
    };

    // code that is executed if return is not done
  }).catch(err => {
    console.log(err);
  });
}