Quiero realizar varias solicitudes de recuperación, cada solicitud tiene una carga diferente, studentID de estudiante en este ejemplo. Cada ciclo cambia el ID de estudiante, pero la carga útil se define como una variable literal de plantilla fuera del ciclo para facilitar la lectura. ¿Hay alguna manera de obtener el valor del iterador de bucle para la carga útil (definida fuera)?
var payload=`{"studentID": ${studentID}}` //expecting studentID to be iterated in loop var myInit = { method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: payload }; for(var studentID = 0; studentID <= 10; studentID++) { fetch(URI, myInit) .then( r => r.json() ) .then( r => console.log(r) .catch(e => console.log(e)); } Los valores de ID de estudiante (0,1,2,3...) no pueden entrar en la plantilla de payload de myInit.
Haz una función en su lugar.
const makeInit = studentID => ({ method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: `{"studentID": ${studentID}}` }); for(var studentID = 0; studentID <= 10; studentID++) { fetch(URI, makeInit(studentID))Tal vez no encadenar manualmente.
const makeInit = studentID => ({ method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({ studentID }) }); for(var studentID = 0; studentID <= 10; studentID++) { fetch(URI, makeInit(studentID))