JS Многократные вызовы функций и одиночные Javascript обещания - PullRequest
0 голосов
/ 27 мая 2020

Вечер Всем,

Новичок в javascript и пытается выполнить этот же приказ, но этого явно не происходит. Когда я запускаю в режиме отладки и устанавливаю точку отладки на getMongoField, остальная часть кода выполняется. Как мне заставить этот код выполняться в том же порядке, сначала получить некоторые поля из mon go, а затем sendFirstmessage, а затем sendSecondMessage (все три функции возвращают обещание), можно ли ввести ожидание внутри обещания?

Спасибо

sentTest: (message) => {
    return new Promise((resolve, reject) => {
        let mongoRecord = null;
        let asResponse;
        let doc = getMongoField('terminals', {'attributes.XYZ': 'ABC'}).then(function (docs) {
            console.info('Before ', mongoRecord)
            mongoRecord = docs
            console.info('After', mongoRecord)
        })

        ts.sendFirstMessage(mongoRecord.attributes.sno, mongoRecord, mongoRecord.attributes.value).then(function (result) {
        //do nothing
        })

        ts.SendSecondMessage(docs.attributes.sno, 'Test', docs, message).then(function (response) {
            resolve(response);
        })

    })
},

Ответы [ 3 ]

1 голос
/ 27 мая 2020

Вы не создаете свое собственное обещание (это явный антипаттерн конструкции обещания ); вместо этого объедините существующие обещания вместе и верните результат.

Вот один из способов сделать это, см. *** комментарии:

sentTest: (message) => {
    let mongoRecord = null;
    let asResponse;
    // *** Return the result of the chain
    return getMongoField('terminals', {'attributes.XYZ': 'ABC'})
    .then(function (docs) {
        // *** Return the promise for the next operation
        return ts.sendFirstMessage(docs.attributes.sno, docs, docs.attributes.value)
            .then(() => {
                // *** Return the promise for the next operation
                // This has to be nested because it uses `docs`
                return ts.SendSecondMessage(docs.attributes.sno, 'Test', docs, message);
            });
    })
},

или

sentTest: (message) => {
    let asResponse;
    // *** Return the result of the chain
    return getMongoField('terminals', {'attributes.XYZ': 'ABC'})
    .then(docs => {
        // *** Return the promise for the next operation
        return ts.sendFirstMessage(docs.attributes.sno, docs, docs.attributes.value)
            // *** Settle the promise from `then` with `docs` so the next handler can see it
            .then(() => docs);
    })
    .then(docs => {
        // *** Return the promise for the next operation
        return ts.SendSecondMessage(docs.attributes.sno, 'Test', docs, message);
    });
},
0 голосов
/ 27 мая 2020

может вводить ожидание внутри обещания?

Можно, но нет смысла иметь его внутри обещания (см. Ссылку в ответе TJ Crowder) . Вам не нужно явное обещание, если вы уже имеете дело с ним.

См. Ниже способ написания кода с помощью async / await:

sentTest: async (message) => {
    let docs = await getMongoField('terminals', {'attributes.XYZ': 'ABC'});
    await ts.sendFirstMessage(docs.attributes.sno, docs, docs.attributes.value);
    return ts.SendSecondMessage(docs.attributes.sno, 'Test', docs, message);
},

Затем позвоните это как await something.sendTest(message).

0 голосов
/ 27 мая 2020

Вам не нужно вводить ожидание внутри обещания. Поскольку функция asyn c - это функции, которые уже возвращают обещание.

https://codesandbox.io/s/confident-banzai-24khs?file= / src / index. js

const obj = {
  sentTest: async message => {
    console.info("Before ", mongoRecord);
    mongoRecord = await getMongoField("terminals", { "attributes.XYZ": "ABC" });
    console.info("After", mongoRecord);

    // probably it needs await too. otherwise it will be a sideeffect
    // which may be evaluated after parent fucntion already return something.
    await ts.sendFirstMessage(
      mongoRecord.attributes.sno,
      mongoRecord,
      mongoRecord.attributes.value
    );


    // By the way you can't access `docs` variable here anyway
    return ts.SendSecondMessage(docs.attributes.sno, "Test", docs, message);
  }
};

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