如何在Javascript中处理从那时起未定义的返回?

时间:2017-10-04 19:38:00

标签: javascript

我想做一些简单的事情。

func1(x).then(func2)

我不会使用func1中的任何返回值(是的,在这种情况下func1会返回undefined),我只想执行func2func1之后,由于undefined没有属性then,我怎么想这样做?

谢谢!

2 个答案:

答案 0 :(得分:-1)

由于func1返回类型可能不是promise,因此必须将func1包装到必须返回promise的新函数中。

示例:https://jsfiddle.net/kingychiu/gewm60as/

假设你有以下函数作为func1,它会根据bool返回一个promise或undefined:

function I_will_return_promise_or_undefined(bool){
    if(bool){
        return new Promise(function(resolve, reject){
        resolve(null);
    });
  }else{
        return undefined
    }
}

你可以这样包装func1:

function wrapper(bool){
    return new Promise(function(resolve, reject){
    var temp = I_will_return_promise_or_undefined(bool);
    if(temp === undefined){
        // resolve it
        resolve(undefined);
    }else{
        // chain promise
        temp.then(function(val){
        resolve(val)
      });
    }
  });
}

最后这就是你想要的:

// null
wrapper(true).then(function(val){
    console.log(true, val);
});

// undefinded
wrapper(false).then(function(val){
    console.log(false, val);
})

答案 1 :(得分:-1)

public async Task<string> AddGroupMember(string accessToken, string groupId, string memberId)
{
    var status = string.Empty;
    string endpoint = $"https://graph.microsoft.com/v1.0/groups/{groupId}/members/$ref";
    string queryParameter = "";

    // pass body data 
    var keyOdataId = "@odata.id";
    var valueODataId = $"https://graph.microsoft.com/v1.0/directoryObjects/{memberId}";

    var values = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>(keyOdataId, valueODataId)
        };
    var body = new FormUrlEncodedContent(values);

    try
    {
        using(var client = new HttpClient())
        {
            using(var request = new HttpRequestMessage(HttpMethod.Post, endpoint + queryParameter))
            {
                request.Content = body;
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                using(var response = await client.SendAsync(request))
                {
                    if (response.StatusCode == HttpStatusCode.NoContent)
                        status = "Member added to Group";
                    else
                        status = $"Unable to add Member to Group: {response.StatusCode}";
                }
            }
        }
    }
    catch (Exception ex)
    {
        status = $"Error adding Member to Group: {ex.Message}";
    }

    return status;
}

您将在控制台中看到: &#39;第一个功能是&#39;并在新的一行: &#39;第二个功能有效&#39;