Вернуть значение из функции внутри обещания - PullRequest
0 голосов
/ 09 октября 2019

Я пытаюсь вернуть массив shiftInfo из функции csData () в обещании.

function crewsense(){

    var request = CS.find({}); 
    request
    .then(result => {
        var created = result[0].created,
            currentTime = moment(),
            diff = (currentTime - created);
        if(diff < 84600000){
            console.log("Current Token is Valid");
            var access_token = result[0].access_token;
            console.log('Obtaining Crewsense Shift Data');
            return access_token
        }else{
            console.log("Current Token is invalid. Updating Token");
            csToken();
        }
    }).then(access_token => {
        csData(access_token) //I am trying to get this function to return async data.

    }).then(shiftInfo => { //I want to use the data here.

})

Вот функция csData:

function csData(csKey) {
    const dayURL = {    
        method: 'get',
        url: 'https://api.crewsense.com/v1/schedule?start='+today+'%2007:30:00&end='+tomorrow+'%2007:30:00',
        headers:{
            Authorization: csKey,
            }
        }

    const request = axios(dayURL)

    request
    .then(result => {
        var shiftInfo = [];
        var thisShift = [];
        var onDuty = result.data.days[moment().format("YYYY-MM-DD")].assignments;
        thisShift.push(result.data.days[moment().format("YYYY-MM-DD")].day_color);
        var persons = [];

        var i = 0;
        for(var i=0; i<onDuty.length; i++){
            let station = onDuty[i].name    
            for(var x=0; x<onDuty[i].shifts.length; x++){
                var person = {
                    name: onDuty[i].shifts[x].user.name,
                    position: onDuty[i].shifts[x].qualifiers[0].name,
                    station: station
                }
            persons.push(person);   
            }   
        }
        shiftInfo = [{thisShift}, {persons}];
        // console.log(shiftInfo)
        return shiftInfo
    })
    .catch(error => console.error('csData error:', error))
}

Я попытался назначить varshiftInfo = csData (access_token) без успеха и несколько других способов вызова функции csData. Я попытался прочитать другие подобные проблемы здесь, и я только что запутался. Если кто-то может указать мне правильное направление или, пожалуйста, указать исправление, я мог бы заставить его щелкнуть в моей голове.

Я ценю время каждого.

Спасибо!

1 Ответ

1 голос
/ 09 октября 2019

Все, что вы return в then, будет передано следующему then обратному вызову. Если вы return a Promise, результат обещания будет отправлен на следующий then обратный вызов:

new Promise((resolve) => {
  // We resolve to the value we want
  resolve("yay");
}).then((value) => {
  // In the first then, value will be "yay"
  console.log("First then:", value);
  // Then we return a new value "yay x2"
  return value + " x2";
}).then((value) => {
  // In this second then, we received "yay x2"
  console.log("Second then:", value);
  // Then we return a promise that will resolve to "yay x2 again"
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(value + " again");
    }, 1000);
  });
}).then((value) => {
  // After a second (when the returned Promise is resolved) we get the new value "yay x2 again"
  console.log("Third then:", value);
  // And now we return a Promise that will reject
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject(new Error("wtf"));
    }, 1000);
  });
}).catch((error) => {
  // This catch on the whole promise chain will catch any promise rejected
  console.log(error.toString());
});

Итак, просто csData должен вернуть созданное обещание, и вам нужно вернуть это обещание в обратный вызов then, который вы хотите:

[...]
}).then(access_token => {
    return csData(access_token) //I am trying to get this function to return async data.
}).then(shiftInfo => { //I want to use the data here.
    console.log(shiftInfo);
}).catch((err) => {
    // Whatever...
});

function csData(csKey) {
    [...]
    return request.then(result => {
    [...]
}

Поскольку вы возвращаете обещание, я рекомендую вам добавить catch за пределами csData и добавить его в цепочку обещаний, которую вы имели ранее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...